<template>
  <div>
    <el-form ref="editForm" :model="editForm" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="选择委托单位" prop="customerId">
            <el-select
              v-model="editForm.customerId"
              placeholder="选择委托单位"
              filterable
              @change="getBuilds"
            >
              <el-option
                v-for="i in userList"
                :key="i.userId"
                :label="i.nickName"
                :value="i.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="选择楼栋" prop="buildingId">
            <el-select v-model="editForm.buildingId" placeholder="选择楼栋" filterable>
              <el-option
                v-for="i in buildList"
                :key="i.id"
                :label="i.name"
                :value="i.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="文件上传" prop="files">
          <!-- accept=".rar,.zip,.doc,.docx,.pdf" -->
            <el-upload
              ref="uploadFile"
              :action="uploadUrl"
              :limit="10"
              multiple
              accept=".pdf"
              :before-remove="beforeRemove"
              :file-list="uploadList"
              :on-success="handleFileSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <el-button size="small" type="primary">上传文件</el-button>
              <div slot="tip" class="el-upload__tip">
                支持格式：PDF
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-col :span="24">
        <div style="display: flex; justify-content: center; margin-top: 1rem">
          <el-button type="primary" style="margin-top: 12px" @click="handleNext">
            暂存并下一步
          </el-button>
        </div>
      </el-col>
    </el-form>
  </div>
</template>
<script>
import { postAiPredict } from "@/api/system/ai";
import { getUserList, getBuildList } from "@/api/contract/contractOrg";
export default {
  data() {
    return {
      editForm: {
        customerId: null, // 委托单位id
        buildingId: null, // 建筑id
        buildingName: null, // 建筑名称
        files: [], // 附件地址
      },
      // 表单校验
      rules: {
        customerId: [{ required: true, message: "委托单位不能为空", trigger: "blur" }],
        buildingId: [{ required: true, message: "建筑不能为空", trigger: "blur" }],
        files: [{ required: true, message: "文件不能为空", trigger: "blur" }],
      },
      userList: [], // 委托单位列表
      buildList: [], // 建筑列表
      uploadList: [],
      // 上传参数
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
    };
  },
  methods: {
    // 初始化
    init(reset = false) {
      this.getUsers();
      if (reset) {
        this.resetForm("editForm");
        this.uploadList = [];
        this.$refs.uploadFile.clearFiles();
      }
    },
    // 获取委托单位列表
    getUsers() {
      getUserList("02").then((res) => {
        this.userList = res.data;
      });
    },
    // 获取建筑列表
    getBuilds() {
      this.editForm.buildingId = null;
      getBuildList({ customerId: this.editForm.customerId }).then((res) => {
        this.buildList = res.rows;
      });
    },
    // 下一步
    handleNext() {
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          this.$emit("refresh", { step: 4, num: this.editForm.files.length });
          postAiPredict(this.editForm)
            .then((res) => {
              if (res.code == 200) {
                this.editForm.buildingName = this.buildList.find(
                  (i) => i.id == this.editForm.buildingId
                ).name;
                this.$cache.local.setJSON("ai-predict", {
                  step: 2,
                  form: this.editForm,
                });
                this.$emit("refresh", {
                  step: 2,
                  form: this.editForm,
                });
              }
            })
            .catch(() => {
              this.$emit("refresh", {
                step: 1,
              });
            });
        }
      });
    },
    // 移除上传
    beforeRemove(file, files) {
      this.uploadList = files;
      this.editForm.files = files
        .filter((i) => i.status == "success")
        .map((i) => {
          return {
            url: i.response.url,
            fileName: i.name,
            fileSize: i.size / 1024 / 1024
          };
        });
    },
    // 文件上传成功处理
    handleFileSuccess(res, file, files) {
      console.log(files)
      this.uploadList = files;
      this.editForm.files = files
        .filter((i) => i.status == "success")
        .map((i) => {
          return {
            url: i.response.url,
            fileName: i.name,
            fileSize: i.size / 1024 / 1024
          };
        });
    },
    // 文件上传前的大小
    beforeAvatarUpload(file) {
      // const typeList = [".rar", ".zip", ".doc", ".docx", ".pdf"];
      const typeList = [".pdf"];
      const lastIndex = file.name.lastIndexOf(".");
      if (lastIndex > -1) {
        const fileType = file.name.substring(lastIndex).toLowerCase();
        if (typeList.includes(fileType)) {
          if (file.size / 1024 / 1024 > 1024) {
            this.$message.error("文件大小不能超过1GB");
            return false;
          } else {
            return true;
          }
        } else {
          this.$message.error("请上传正确的文件格式");
          return false;
        }
      } else {
        return false;
      }
    },
  },
};
</script>
